package com.ruoyi.system.service.impl;

import java.util.Iterator;
import java.util.List;

import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.DrtypemodeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.DrtypeinfoMapper;
import com.ruoyi.system.service.IDrtypeinfoService;

/**
 * 设备类型管理Service业务层处理
 * 
 * @author yaozh
 * @date 2024-02-28
 */
@Service
public class DrtypeinfoServiceImpl implements IDrtypeinfoService 
{
    @Value("${centralDatabase.dbName}")
    private String centralDatabase;

    private static final Logger log = LoggerFactory.getLogger(DrtypeinfoServiceImpl.class);

    @Autowired
    private DrtypeinfoMapper drtypeinfoMapper;

    /**
     * 保存设备（子系统）类型。本质上是从 中心库.drtypeinfo表复制那些在页面上 勾选的项 到对应项目的drtypeinfo表（如项目111lvleng的drtypeinfo表，如：111lvleng.drtypeinfo）
     * @param dbName
     * @param drTypeIds
     */
    @Override
    public void moveDrTypeAndModel(String dbName, String drTypeIds,List<Qstag> qsTagList) {
        String[] drTypeIdArray = drTypeIds.split(",",-1);
        Integer drTypeId;
        String dbNameCenter = centralDatabase;//
        for(String drTypeIdStr : drTypeIdArray){
            drTypeId =  Integer.valueOf(drTypeIdStr);
            Drtypeinfo drTypeInfo = drtypeinfoMapper.findObjectByDrtypeid(dbNameCenter,drTypeId);//从 中心库 中根据设备类型ID返回设备类型。select * from `中心库`.drtypeinfo WHERE drtypeid=?
            if(drTypeInfo != null){
                drtypeinfoMapper.deleteDrtypeinfoById(dbName, drTypeId);//根据dbName和设备类型ID删除设备类型。delete from `111lvleng`.drtypeinfo where drtypeid=?
                drtypeinfoMapper.insertObject(dbName, drTypeInfo);//根据dbName将 设备类型信息 插入到 项目库的设备类型表中。insert into `111lvleng`.drtypeinfo (drtypeid,drtypename,parentid, drtypeiconid,isshow,isdrtype,iscustom_type,picid) values (?,?,?, ?,?,?, ?, ?)
            }
        }
    }

    @Override
    public List<Drtypeinfo> findAllDrtypeAndDrReturnList(String dBname,Integer iscustomType) {
        List<Drtypeinfo> drtypeinfoList = drtypeinfoMapper.findAllDrtypeAndDr(dBname,iscustomType);
        return drtypeinfoList;
    }

    /**
     * 查询设备类型管理
     * 
     * @param drtypeid 设备类型管理主键
     * @return 设备类型管理
     */
    @Override
    public Drtypeinfo selectDrtypeinfoByDrtypeid(Long drtypeid, String dbName)
    {
        return drtypeinfoMapper.selectDrtypeinfoByDrtypeid(drtypeid,dbName);
    }

    /**
     * 查询设备类型管理列表
     * 
     * @param drtypeinfo 设备类型管理
     * @return 设备类型管理
     */
    @Override
    public List<Drtypeinfo> selectDrtypeinfoList(Drtypeinfo drtypeinfo, String dbName)
    {
        return drtypeinfoMapper.selectDrtypeinfoList(drtypeinfo,dbName);
    }

    @Override
    public List<Drtypeinfo> selectDrTypeForAll(String dbName){
        return drtypeinfoMapper.selectDrTypeForAll(dbName);
    }

    @Override
    public List<DeviceTreeSelect> selectDrTypeTreeList(Drtypeinfo drtypeinfo, String dbName) {
        List<Drtypeinfo> drTypeList = SpringUtils.getAopProxy(this).selectDrtypeinfoList(drtypeinfo,dbName);
        return buildDeptTreeSelect(drTypeList);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param drTypeList 设备类型列表
     * @return 树结构列表
     */
    @Override
    public List<Drtypeinfo> buildDeptTree(List<Drtypeinfo> drTypeList)
    {
        List<Drtypeinfo> returnList = new ArrayList<Drtypeinfo>();
        List<Long> tempList = drTypeList.stream().map(Drtypeinfo::getDrtypeid).collect(Collectors.toList());
        for (Drtypeinfo drTypeInfo : drTypeList)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(drTypeInfo.getParentId()))
            {
                recursionFn(drTypeList, drTypeInfo);
                returnList.add(drTypeInfo);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = drTypeList;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param drTypeList 设备类型列表
     * @return 下拉树结构列表
     */
    @Override
    public List<DeviceTreeSelect> buildDeptTreeSelect(List<Drtypeinfo> drTypeList)
    {
        List<Drtypeinfo> deptTrees = buildDeptTree(drTypeList);
        return deptTrees.stream().map(DeviceTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 新增设备类型管理
     * 
     * @param drtypeinfo 设备类型管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDrtypeinfo(Drtypeinfo drtypeinfo, String dbName)
    {
        int rows = drtypeinfoMapper.insertDrtypeinfo(drtypeinfo,dbName);
        insertDrtypemode(drtypeinfo,dbName);
        return rows;
    }

    /**
     * 修改设备类型管理
     * 
     * @param drtypeinfo 设备类型管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDrtypeinfo(Drtypeinfo drtypeinfo, String dbName)
    {
        drtypeinfoMapper.deleteDrtypemodeByDrtypeid(drtypeinfo.getDrtypeid(),dbName);
        insertDrtypemode(drtypeinfo,dbName);
        return drtypeinfoMapper.updateDrtypeinfo(drtypeinfo,dbName);
    }

    /**
     * 批量删除设备类型管理
     * 
     * @param drtypeids 需要删除的设备类型管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDrtypeinfoByDrtypeids(Long[] drtypeids, String dbName)
    {
        drtypeinfoMapper.deleteDrtypemodeByDrtypeids(drtypeids,dbName);
        return drtypeinfoMapper.deleteDrtypeinfoByDrtypeids(drtypeids,dbName);
    }

    /**
     * 删除设备类型管理信息
     * 
     * @param drtypeid 设备类型管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDrtypeinfoByDrtypeid(Long drtypeid, String dbName)
    {
        drtypeinfoMapper.deleteDrtypemodeByDrtypeid(drtypeid,dbName);
        return drtypeinfoMapper.deleteDrtypeinfoByDrtypeid(drtypeid,dbName);
    }

    /**
     * 新增设备类型模板信息
     * 
     * @param drtypeinfo 设备类型管理对象
     */
    public void insertDrtypemode(Drtypeinfo drtypeinfo, String dbName)
    {
        List<Drtypemode> drtypemodeList = drtypeinfo.getDrtypemodeList();
        Long drtypeid = drtypeinfo.getDrtypeid();
        if (StringUtils.isNotNull(drtypemodeList))
        {
            List<Drtypemode> list = new ArrayList<Drtypemode>();
            for (Drtypemode drtypemode : drtypemodeList)
            {
                drtypemode.setDrtypeid(drtypeid);
                list.add(drtypemode);
            }
            if (list.size() > 0)
            {
                drtypeinfoMapper.batchDrtypemode(list,dbName);
            }
        }
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Drtypeinfo> list, Drtypeinfo t)
    {
        // 得到子节点列表
        List<Drtypeinfo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Drtypeinfo tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Drtypeinfo> getChildList(List<Drtypeinfo> list, Drtypeinfo t)
    {
        List<Drtypeinfo> tlist = new ArrayList<Drtypeinfo>();
        Iterator<Drtypeinfo> it = list.iterator();
        while (it.hasNext())
        {
            Drtypeinfo n = (Drtypeinfo) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDrtypeid().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Drtypeinfo> list, Drtypeinfo t)
    {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public String importDrTypeInfo(List<Drtypeinfo> regList, Boolean isUpdateSupport, String operName, String dbName){
        if (regList == null || regList.size() == 0)
        {
            throw new ServiceException("导入项目设备类型定义数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Drtypeinfo drTypeInfo : regList)
        {
            try{
                // 验证是否存在，parentId + drTypeName 联合唯一主键（业务逻辑上）
                Long parentId = drTypeInfo.getParentId();
                String drTypeName = drTypeInfo.getDrtypename();
                Drtypeinfo tempDrTypeInfo = drtypeinfoMapper.selectDrTypeInfoByParentIdAndDrTypeName(parentId,drTypeName,dbName);
                if (tempDrTypeInfo == null)
                {
                    drTypeInfo.setCreateBy(operName);
                    drtypeinfoMapper.insertDrtypeinfo(drTypeInfo,dbName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、设备类型父ID " + drTypeInfo.getParentId() + "、设备类型名称 " + drTypeInfo.getDrtypename() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    drTypeInfo.setDrtypeid(tempDrTypeInfo.getDrtypeid());
                    drTypeInfo.setUpdateBy(operName);
                    drtypeinfoMapper.updateDrtypeinfo(drTypeInfo,dbName);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、设备类型父ID " + drTypeInfo.getParentId() + "、设备类型名称 " + drTypeInfo.getDrtypename() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、设备类型父ID " + drTypeInfo.getParentId() + "、设备类型名称 " + drTypeInfo.getDrtypename() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、设备类型父ID " + drTypeInfo.getParentId() + "、设备类型名称 " + drTypeInfo.getDrtypename() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
